package com.demospringboot.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.demospringboot.common.vo.Result;
import com.demospringboot.system.entity.RepairRequest;
import com.demospringboot.system.entity.Role;
import com.demospringboot.system.entity.User;
import com.demospringboot.system.mapper.RepairRequestMapper;
import com.demospringboot.system.service.IUserService;
import com.demospringboot.utils.JwtUtil;
import com.demospringboot.utils.PasswordUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/api/logistics-staff")
public class LogisticsStaffController {
    @Autowired
    private IUserService userService;
    @Autowired
    private RepairRequestMapper repairRequestMapper;

    // 管理员查询所有后勤人员
    @GetMapping("/all")
    public Result<List<User>> allLogisticsStaff(HttpServletRequest request) {
        if (!isAdmin(request)) {
            return Result.fail("未登录或token缺失");
        }
        List<User> list = userService.lambdaQuery().eq(User::getRole, Role.LOGISTICS_STAFF).list();
        return Result.success(list);
    }

    // 管理员新增后勤人员
    @PostMapping("/add")
    public Result<?> addLogisticsStaff(@RequestBody User user, HttpServletRequest request) {
        if (!isAdmin(request)) {
            return Result.fail("未登录或token缺失");
        }
        // 检查用户名是否已存在
        User existingUser = userService.lambdaQuery().eq(User::getUsername, user.getUsername()).one();
        if (existingUser != null) {
            return Result.fail("用户名已存在");
        }

        // 对密码进行加密
        user.setPassword(PasswordUtils.md5AndSalt(user.getPassword()));
        user.setRole(Role.LOGISTICS_STAFF);
        userService.save(user);
        return Result.success("添加成功");
    }

    // 管理员修改后勤人员
    @PutMapping("/update")
    public Result<?> updateLogisticsStaff(@RequestBody User user, HttpServletRequest request) {
        if (!isAdmin(request)) {
            return Result.fail("未登录或token缺失");
        }
        // 如果密码不为空，则进行加密更新
        if (user.getPassword() != null && !user.getPassword().isEmpty()) {
            user.setPassword(PasswordUtils.md5AndSalt(user.getPassword()));
        } else {
            // 否则，不更新密码字段
            user.setPassword(null);
        }
        user.setRole(Role.LOGISTICS_STAFF);
        userService.updateById(user);
        return Result.success("修改成功");
    }

    // 管理员删除后勤人员
    @DeleteMapping("/{id}")
    public Result<?> deleteLogisticsStaff(@PathVariable Long id, HttpServletRequest request) {
        if (!isAdmin(request)) {
            return Result.fail("未登录或token缺失");
        }
        if (repairRequestMapper.selectCount(
                new QueryWrapper<RepairRequest>().eq("handler_user_id", id)
        ) > 0) {
            return Result.fail("该后勤人员有处理中的报修单，无法删除");
        }
        userService.removeById(id);
        return Result.success("删除成功");
    }

    // 判断是否为管理员
    private boolean isAdmin(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token == null || token.trim().isEmpty()) {
            return false;
        }
        String username = JwtUtil.getUsername(token);
        User user = userService.lambdaQuery().eq(User::getUsername, username).one();
        return user != null && user.getRole() == Role.ADMIN;
    }
} 